<%@ taglib prefix="shiro" uri="http://shiro.apache.org/tags" %>
<%--
  Created by IntelliJ IDEA.
  User: asus
  Date: 2020/4/20
  Time: 8:23
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="true" %>
<html>
<head>
    <title>用户管理</title>
    <%@include file="/comm/head.jsp"%>
    <%--<style>
        .ivu-from-item{
            margin-bottom: 0px;
        }
    </style>--%>
</head>
<body>
<div id="root">
    <modal v-model="userGrantFlag" title="用户授权" @on-ok="grant">
        <i-table :columns="myColumns" :data="myData" :height="400" @on-selection-change=" uSelection=arguments[0]" border stripe ><%--只要选中现发生变化时就会触发，返回值为selection，已选项--%>

        </i-table>
    </modal>
    <modal v-model="updateFlag" title="修改员工" @on-ok="update()">
        <i-form :label-width="80" style="padding:30px">
            <form-item label="出生年月">
                <date-picker type="datetime" format="yyyy-MM-dd" v-model="user.birthday" size="large"/>
            </form-item>
            <form-item label="部门名称">
                    <i-select  v-model="user.userOrg"   style="width: 110px">
                        <i-Option v-for="item in orgList" :value="item.id" v-bind:key="item.id" />{{item.orgName}}</i-Option>
                    </i-select>

            </form-item>

            <form-item label="联系地址">
                <i-input v-model="user.address" size="large"/>
            </form-item>

            <form-item label="真实姓名">
                <i-input v-model="user.username" size="large"/>
            </form-item>
            <form-item label="登录名">
                <i-input v-model="user.userCode" size="large"/>
            </form-item>
            <form-item label="电话号码">
                <i-input v-model="user.phone" size="large"/>
            </form-item>

        </i-form>

    </modal>
    <modal v-model="addFlag" title="添加员工"  >
        <i-form :label-width="70"  :model="user"  ref='user'  style="padding: 30px" :rules='ruleValidate'>
            <form-item label="性别" prop="gender">
                <radio-group v-model="user.gender">
                    <radio :label="1">男</radio>
                    <radio :label="2">女</radio>
                </radio-group>
            </form-item>
        <form-item label="部门名称" prop="userOrg">
            <i-select v-model="user.userOrg" style="width: 180px">
                <i-Option v-for="item in orgList" :value="item.id" >{{item.orgName}}</i-Option>
            </i-select>
        </form-item>
        <form-item label="出生年月" <%--prop="birthday"--%>>
            <row>
                <Col span="11">
                <date-picker type="date" placeholder="请输入出生日期" v-model="user.birthday" ></date-picker>
                </Col>
            </row>
        </form-item>
            <form-item label="登录名"    prop="userCode">
                <i-input v-model="user.userCode"  placeholder="请输入登录名" size="large" <%--@blur.native.capture="checkMing"--%>/>
            </form-item>
           <form-item label="真实性名"<%-- prop="username"--%>>
               <i-input v-model="user.username" placeholder="请输入用户名" size="large"/>
           </form-item>
           <form-item label="电话号码" <%--prop="phone"--%>>
               <i-input v-model="user.phone" placeholder="请输入手机号" size="large"/>
           </form-item>
            <form-item label="联系地址" <%--prop="phone"--%>>
                <i-input v-model="user.address" placeholder="请输入联系地址" size="large"/>
            </form-item>

            <form-item label="初始密码">
                <span style="color: red">123456</span>
            </form-item>


        </i-form>
        <div slot="footer">
            <i-button type="error" size="large" @click="add('user')">确定</i-button>

        </div>
    </modal>

<Collapse value="search">
    <Panel name="search">
        条件查询
        <p slot="content">
            <i-form inline :label-width="80">
        <form-item label="登陆名:">
            <i-input type="text" v-model="userVo.userCode"/>
        </form-item>
                <form-item label="真实姓名:">
                    <i-input type="text" v-model="userVo.userName"/>
                </form-item>
                <form-item label="性别" prop="gender">
                    <radio-group v-model="userVo.gender">
                        <radio :label="1">男</radio>
                        <radio :label="2">女</radio>
                    </radio-group>
                </form-item>
                <form-item label="联系电话:">
                    <i-input type="text" v-model="userVo.phone"/>
                </form-item>
                <form-item label="联系地址:">
                    <i-input type="text" v-model="userVo.address"/>
                </form-item>
              <%--  <form-item label="用户角色:">
                   <i-select v-model="userVo.userRole" style="width: 110px">
                       <i-option value="">【不限】</i-option>
                       <i-Option v-for="item in roleList" :value="item.id" :key="item.id">{{item.roleName}}</i-Option>
                   </i-select>
                </form-item>--%>
                <form-item label="用户部门">
                    <i-select v-model="userVo.userOrg" style="width: 110px">
                        <i-option value="">【不限】</i-option>
                        <i-Option v-for="item in orgList" :value="item.id" :key="item.id">{{item.orgName}}</i-Option>
                    </i-select>
                </form-item>
                <form-item label="出生日期:">
                    <row>
                    <col span="12"> <date-picker @on-change="userVo.startDate=$event"  placeHolder="请输入起始日期" style="width: 150px" type="date" ></date-picker></col>
                        <col span="12"> <date-picker @on-change="userVo.endDate=$event"   placeHolder="请输入结束日期" style="width: 150px" type="date" ></date-picker></col>
                    </row>
                </form-item>

                    <i-button type="primary" style="margin-left:20px" @click="pageNo=1;searchUserList();">搜索</i-button>

    </i-form>
        </p>
    </Panel>
</Collapse>
    <card>
        <shiro:hasPermission name="user:add">
        <i-button type="success" @click="toAdd">添加员工</i-button>
        </shiro:hasPermission>
        <i-button type="info" @click="exportExcel">导出Excel</i-button>
        <i-button type="info" @click="exportPdf">打印预览</i-button>
        <%-- <shiro:hasPermission name="user:grant">
        <i-button type="primary" @click="userGrant">用户授权</i-button>
        </shiro:hasPermission>--%>

    </card>

    <i-table :columns="columns" :data="pageResult.rows" :height="300"  @on-selection-change="tableSelection=arguments[0]"  border stripe>
        <template slot-scope="{row}" slot="gender"><%--slot-scope有3个参数当前行数据row当前列数据column当前行序号index--%>
            <span>{{row.gender==1?"男":"女"}}</span>
        </template>

        <template slot-scope="{row}" slot="roleName"><%--slot-scope有3个参数当前行数据row当前列数据column当前行序号index--%>
            <span>{{row.role.roleName}}</span>
        </template>
        <template slot-scope="{row}" slot="userOrg">
            <span>{{row.org.orgName}}</span>
        </template>


        <template slot-scope="{row,index}"  slot="action">
            <shiro:hasPermission name="user:update">
            <i-button type="warning" @click="toUpdate(row)" size="small">修 改</i-button>
            </shiro:hasPermission>
            <shiro:hasPermission name="user:del">
            <i-button type="error" @click="del(row,index)" size="small">删 除</i-button><!--row代表此行数据-->
            </shiro:hasPermission>
        </template>
    </i-table>

<%--<Page :total="pageResult.total" :page-size="pageSize" @on-change="changePageNo"/>--%>
  <Page :total="pageResult.total"
        :page-size="pageSize"<%--每页条数--%>
        <%--:current.sync="pageNo"    =pageNo=arguments[0];searchUserList();当前页码，支持.sync修饰符,同步
        @on-change="searchUserList"返回改变后的页码,这两行代码相当于下面一行代码--%>
          @on-change="pageNo=arguments[0];searchUserList();"
       <%-- @on-change="searchUserList"--%>
        show-sizer<%--是否显示分页，用来改变page-size--%>
        :page-size-opts="[5,10,15]"<%--每页条数切换的配置--%>
       <%-- @on-page-size-change="changPageSize"--%>
        @on-page-size-change="pageSize=arguments[0];searchUserList();"<%--切换每页数时的回调，返回切换后的每页条数--%>
  />
</div>


<script>


    new Vue({
        el:"#root",
        data(){
            return{
                myColumns:[

                    {type:"selection",width:60,align:"center"},//自动开启多选功能
                    {key:"roleName",title:"角色名称"},
                    {key:"modifyDate",title:"最后修改时间"},

                ],


                myData:[],
                columns:[
                    // {type:"selection",width:60,align:"center"},//自动开启多选功能
                    {key:"id",title:"编号",width:100},
                    {key:"userCode",title:"登录名",width:130},
                    {key:"username",title:"真实姓名",width:140},
                    {slot:"gender",title:"性别",width:60},
                    {key:"birthday",title:"出生年月",width:150},
                    {key:"phone",title:"电话",width:140},
                    { key:"address",title:"用户地址",width:300},
                    /*{ key:"userRole",title:"角色编号"},*/
                    // { slot:"roleName",title:"角色名称"},
                    {title:"部门名称",slot: "userOrg"},
                    {title:"操作",slot:"action",width:300}
                ],

                //  data:[],
                pageResult:{
                    rows:[],
                    total:50
                },
                updateFlag:false,
                userVo:{},
                roleList:[],
                orgList:[],

                pageNo:1,
                pageSize:5,
                tableSelection:[],
                uSelection:[],
                uploadFlag:false,
                uploadForm:{
                    id:null,
                    attachPath:null,
                    attachDescr:null
                },
                userGrantFlag:false,
                img:null,//为了回显
                org:{ },
                user:{
                    gender:'',
                    userRole:'',
                    birthday:'',

                    username:'',
                    phone:'',
                    userCode:'',
                    userOrg:''

                },


                ruleValidate: {
                    /*  username: [
                          { required: true, message: '用户姓名不能为空', trigger: 'blur' }
                      ],*/
                    birthday: [
                        { required: true, type: 'date',   message: '请选择出生日期', trigger: 'blur' }
                    ],

                    phone: [
                        { required: true, message: '请填写电话号码', trigger: 'blur' }
                    ],
                    gender: [
                        { required: true, type: 'number', message: '请选择性别', trigger: 'change' }
                    ],
                    userRole: [
                        { required: true, message: '请选择用户角色', trigger: 'blur' }
                    ],
                    userCode:
                        [{
                            required: true,
                            trigger: 'blur',
                            validator: (rule, value, callback) => {
                                asyValid(rule, value, callback)
                            }
                        }],
                    userOrg:
                        [{required: true, type: 'number', message: '请选择部门名称，这是必填项', trigger: 'change'}],
                },
               const :asyValid=(rule,value,callback)=>{
                    if (!value) {
                       return callback(new Error("请输入用户名"));
                    } else if (!/^[a-zA-Z\d]+$/.test(value)) {
                        return callback(new Error("请正确输入用户名"))
                    } else {
                    let json=this.user.userCode;
                    // console.log(json)
                    axios.post('/sys/user/select',{
                        userCode : json,
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}   //跨域
                    }).then(function (dat){
                        if (dat.data == "1"){
                            return callback(new Error('登录名已存在'))
                        } else{
                            return callback();
                        }

                    }).catch((e)=>{
                        iview.Message.error(`校验失败${e}`);
                        return callback()
                    })
                }
                },
                addFlag:false,

            }

            },

        methods:{

            searchUserList(){
              /*  axios.get(`${ctx}/sys/user/list`,Qs.stringify(this.userVo))*/
               axios.get(`${ctx}/sys/user/search/${this.pageNo}/${this.pageSize}`,{params:this.userVo})//post支持json，get支持formDate
                    .then(({data})=>{
                        this.pageResult=data.result;
                    });
            },

           searchRoleList(){
               axios.get(`${ctx}/sys/role/list`)
                   .then(({data})=>{
                       this.roleList=data.result;
                   });
           },

            toUpdate(row){
                this.user.userOrg=row.org.id;
                this.user=row;
                this.updateFlag=true;
            },
            update(){
                let params=Qs.stringify(this.user,{serializeDate:(date)=>{
                        return moment(date).format("YYYY-MM-DD");
                    }});
                axios.post(`${ctx}/sys/user/update`,Qs.parse(params))
                    .then(({data})=>{
                        this.updateFlag=false;//关闭模态框
                        iview.Message.success({content:data.msg});
                        this.searchUserList();
                    });
            },
           searchOrgList(){
                axios.get(`${ctx}/cus/org/search`)
                    .then(({data})=>{
                        this.orgList=data.result;
                    })
           },
           toUpload(row){

                this.uploadForm.id=row.id;

                this.uploadFlag=true;
           },
           doBeforeUpload(file){
               const reader=new FileReader();
               reader.readAsDataURL(file);//读取的是本地的图片
               reader.onloadend = ()=>{
                   this.img = reader.result;
               }/*//这三行代码是预览图片*/

           },
           toAdd(){
                this.user = {};
                this.addFlag=true;

           },
           add(user){
               this.$refs[user].validate((valid) => {
                   if (valid) {
                       axios.post(`${ctx}/sys/user/add`,this.user)
                           .then(({data})=>{
                               this.addFlag=false;//关闭模态框
                               iview.Message.success({content:data.msg});
                               this.searchUserList();

                           });
                   } else {
                       this.$Message.error('请看好您的错误选项!');
                   }
               })

           },

           userGrant(){


               if(this.tableSelection.length!=1){
                   iview.Modal.error({
                       title:"信息提示",
                       content:"请至少选择一项用户进行授权"
                   });
                   return;
               }

               axios.get(`${ctx}/sys/role/userlist?id=${this.tableSelection[0].id}`)
                   .then(({data})=>{
                       this.myData=data.result;
                       this.userGrantFlag=true;
               })

           },
           del(row,index){  //一般情况下查询删除用get()增加修改用post()
               let _this=this;
               let flag=iview.Modal.confirm({
                   title:"你确定要删除吗？",
                   content:"该操作不可逆，请谨慎操作。",
                   onOk(){
                       axios.get(`${ctx}/sys/user/del?id=${row.id}`)
                           .then(({data})=>{
                               iview.Message.success({content:data.msg});
                               _this.pageResult.rows.splice(index,1);

                           })
                   },
               });

           },

           grant(){

                if(this.uSelection.length==0){
                    iview.Modal.confirm({
                        title:"信息提示",
                        content:"您确定还是原来的角色名称吗?",
                        onOk: () => {
                            this.$Message.info('您的角色名称未改变，还是原来的角色名称');
                        },
                        onCancel: () => {
                            axios.get(`${ctx}/sys/role/userlist?id=${this.tableSelection[0].id}`)
                                .then(({data})=>{
                                    this.myData=data.result;
                                    this.userGrantFlag=true;
                                })
                        }
                    });
                    return;
                }
                if(this.uSelection.length>1){
                    iview.Modal.confirm({
                        title:"信息提示",
                        content:"请选择一项只能选择一项角色名称",
                        onOk:()=>{
                            axios.get(`${ctx}/sys/role/userlist?id=${this.tableSelection[0].id}`)
                                .then(({data})=>{
                                    this.myData=data.result;
                                    this.userGrantFlag=true;
                                })
                        }
                    });
                    return;
                }
               var params=`userId=${this.tableSelection[0].id}`;
                var roleId=`userRole=${this.uSelection[0].id}`;
           params+="&"+roleId;
                axios.get(`${ctx}/sys/user/update?${params}`)
                    .then(({data})=>{
                        this.userGrantFlag=false;
                        iview.Message.success({content:data.msg});
                        this.searchUserList();
                    })
           },
           uploadSuccess(response){
               console.log(response);
               this.uploadForm.attachPath=response.result.attachPath;
               iview.Message.success("上传成功!");
           },
           updateAttach(){
             axios.post(`${ctx}/sys/user/updateAttach`,this.uploadForm)
                 .then(({data})=>{
                     this.updateFlag=false;
                     iview.Message.success({content:data.msg});
                     this.searchUserList();
                 })


           },
            exportExcel(){
                location.href=`${ctx}/sys/yuan/exportExcel`
            },
            exportPdf(){
                location.href=`${ctx}/sys/yuan/exportPdf`
            }

        /*    checkMing(rule,value,cb){

                this.errorMsg1 = "";

                if(this.user.userCode!=""){
                    let json=this.user.userCode;
                    axios.post('/sys/user/select',{
                        userCode : json,
                        headers: {'Content-Type': 'application/x-www-form-urlencoded'}   //跨域
                    }).then(function (dat){
                        if (dat.data == "1"){
                            this.errorMsg1 = '<span style="color: green">用户名已存在</span>'
                        }

                })
                }
            }*/
          /* changPageSize(){
               this.pageSize=arguments[0];
               this.searchUserList();
           },*/
          /* changPageSize(pageSize){
                this.pageSize=pageSize;
                this.searchUserList();
           },*/
          /* changePageNo(pageNo){
        this.pageNo=pageNo;
        this.searchUserList();
           }*/

       },
        mounted(){
           this.searchRoleList();
           this.searchUserList();
           this.searchOrgList();
        }

    });
</script>
</body>
</html>
